package com.simon.hse.http;

import android.util.Log;

import com.google.gson.Gson;
import com.simon.hse.MyApplication;
import com.simon.hse.activity.LoginActivity;
import com.simon.hse.utils.IntentUtils;
import com.simon.hse.utils.PreferencesUtils;

import okhttp3.OkHttpClient;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * http 请求
 */
@SuppressWarnings("all")
public class HttpManager {
    private static RequestService requestService;
    private static int REQUEST_COUNT = 0;

    //请求处理成功
    public static final int SUCCESS = 200;
    //未认证、未登录、或票据过期未刷新
    public static final int SUCCESS_NO_LOGIN = 401;
    //未授权、无权限访问的API接口
    public static final int SUCCESS_NO_PERMISSION = 403;
    //传入接口参数不合规，如数据类型、Json结构
    public static final int SUCCESS_CODE400 = 400;
    //API异常、异常处理
    public static final int SUCCESS_CODE500 = 500;

    private HttpManager() {
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(new WriteCookiesInterceptor())
                .addInterceptor(new ReadCookiesInterceptor())
                // .addInterceptor(new RetrofitLogInterceptor())
                .build();

        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(ApiConstanse.BASE_URL)
                .addConverterFactory(ScalarsConverterFactory.create())
                // .addConverterFactory(GsonConverterFactory.create())
                .client(okHttpClient)
                .build();

        requestService = retrofit.create(RequestService.class);
    }

    public static HttpManager getInstance() {
        return SafeMode.mHttpManager;
    }

    /**
     * static final 保证了实例的唯一和不可改变
     */
    private static class SafeMode {
        private static final HttpManager mHttpManager = new HttpManager();
    }

    /**
     * 请求体
     * @param object
     * @return
     */
    public RequestBody requestBody(Object object) {
        Gson gson = new Gson();
        String toJson = gson.toJson(object);
        Log.e("xxxxx", "requestBody============" + toJson);
        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), toJson);
        return body;
    }

    /**
     * 请求服务
     * @return
     */
    public RequestService requestService() {
        return requestService;
    }

    /**
     * 请求回调
     * @param call
     * @param commonCallBack
     */
    public void requestCallBack(Call<String> call, CommonCallBack<String> commonCallBack) {
        call.enqueue(new retrofit2.Callback<String>() {
            @Override
            public void onResponse(Call<String> call, Response<String> response) {
                Log.i("Simon","onResponse = "+response.code());
                switch (response.code()) {
                    case SUCCESS:
                        commonCallBack.requestSuccess(response.body());
                        Log.e("xxxxx", "onResponse ======== "+response.body());
                        break;
                    case SUCCESS_NO_LOGIN:
                        PreferencesUtils.putBoolean("LOGIN_STATE", false);
                        IntentUtils.startNewTaskActivity(MyApplication.getInstance(), LoginActivity.class);
                        break;
                    default:
                        commonCallBack.requestError(response.message());
                        break;
                }
            }

            @Override
            public void onFailure(Call<String> call, Throwable t) {
                Log.i("Simon","onFailure = "+t.getMessage());
                commonCallBack.requestError(t.getMessage());
            }
        });
    }

    /**
     * 更新cookie
     *
     * @param commonCallBack
     */
//    public void updateCookies(final CommonCallBack<String> commonCallBack) {
//        String phone = PreferencesUtils.getString("USERNAME", "admin");
//        String password = PreferencesUtils.getString("PASSWORD", "123456");
//
//        LoginInput loginInput = new LoginInput();
//        loginInput.setLoginName(phone);
//        loginInput.setPassword(password);
//        Gson gson = new Gson();
//        String toJson = gson.toJson(loginInput);
//
//        RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), toJson);
//        RequestService service = HttpManager.getInstance().request();
//        /*Call<LoginOutput> call = service.login(body);
//        call.enqueue(new retrofit2.Callback<LoginOutput>() {
//            @Override
//            public void onResponse(Call<LoginOutput> call, Response<LoginOutput> response) {
//                LoginOutput login = response.body();
//                Log.i("Simon", "updateCookie onFailureeee = ");
//                REQUEST_COUNT++;
//                if (REQUEST_COUNT < 5) {
//                    if (login == null) {
//                        ToastUtils.getInstance().showShortToast("服务器异常!");
//                        return;
//                    }
//                   // commonCallBack.receiveMsg(login.getResult());
//                } else {
//                    commonCallBack.receiveMsg("Faild");
//                }
//            }
//
//            @Override
//            public void onFailure(Call<LoginOutput> call, Throwable t) {
//                Log.i("Simon", "updateCookie onFailure = " + t.getMessage());
//            }
//        });*/
//    }
}
